﻿using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework;
using IWMAG.Core.Hitboxes;

namespace IWMAG.Core.Objects {
    public class Character : CollidingGameObject {
        protected KeyboardState State;
        public int Speed = 200;
        public bool Jumping { get; protected set; }
        protected Vector2 JumpSpeed = Vector2.Zero;

        public Character() : base() {
            Position = new Vector2(320, 240);
        }

        public override void Load(int id, Level level) {
            level.Messages.SubscribeTo(id, EventType.OnInput);
            Hitbox = new RectHitbox(new Rectangle(0, 0, 10, 10));

            base.Load(id, level);
        }

        public override void Initialize(ContentManager content) {
            Sprite = new Graphic(content.Load<Texture2D>("pixel"), 1, 1);

            base.Initialize(content);
        }

        public override void Update(float elapsed) {
            if (State.IsKeyDown(Keys.Right)) {
                MoveRelative(Vector2.UnitX * Speed * elapsed);
            } else if (State.IsKeyDown(Keys.Left)) {
                MoveRelative(-Vector2.UnitX * Speed * elapsed);
            }

            if (State.IsKeyDown(Keys.Space) && !Jumping) {
                JumpSpeed = -Vector2.UnitY * 240;
                Jumping = true;
            }
            
            bool hit = false;
            if (Jumping) {
                hit = !MoveRelative(JumpSpeed * elapsed);
                JumpSpeed += Level.Script.GetValue<Vector2>("gravity") * elapsed;
            } else if (!CheckRelative(Vector2.UnitY)) {
                Jumping = true;
                JumpSpeed = Level.Script.GetValue<Vector2>("gravity") * elapsed;
            }

            if (hit && JumpSpeed.Y < 0) {
                JumpSpeed.Y = 0;
            } else if (hit && JumpSpeed.Y >= 0) {
                Jumping = false;
            }

            base.Update(elapsed);
        }

        public override void Draw(float elapsed, SpriteBatch batch) {
            base.Draw(elapsed, batch);
        }

        public override void ReceiveMessage(Messaging.Message msg) {
            switch (msg.Type) {
                case EventType.OnInput:
                    State = msg.Data.Keyboard;
                    break;
            }
        }
    }
}